<template>
  <a-upload
    list-type="picture-card"
    :file-list="fileList"
    :custom-request="customRequest"
    @change="handleChange"
    @preview="handlePreview"
    :before-upload="beforeUpload"
  >
    <div v-if="!url">
      <plus-outlined />
      <div style="margin-top: 8px">上传图片</div>
    </div>
    <img v-else :src="url" alt="" style="width: 100px;height: 100px;" />
  </a-upload>
</template>

<script setup>
import { ref } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
defineProps({
  url:{
    type:String,
    default:''
  }
})
const fileList = ref([]);
const maxCount = 1; // 最大上传数量
const emit = defineEmits(['uploadSuccess'])
// 自定义上传函数
const customRequest = async (options) => {
  const { file, onProgress = ()=>{}, onSuccess= ()=>{}, onError= ()=>{} } = options;
  
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    // 模拟上传进度
    let progress = 0;
    const progressInterval = setInterval(() => {
      progress += 10;
      onProgress({ percent: progress });
      if (progress >= 90) clearInterval(progressInterval);
    }, 200);
    
    const token = sessionStorage.getItem("token") || "";
    // 实际API请求
    const response = await fetch('http://localhost:8090/api/upload/file', {
      method: 'POST',
      headers: {
        Authorization: token,
      },
      body:formData,
      onUploadProgress: (event) => {
        onProgress({ percent: Math.round((event.loaded / event.total) * 100) });
      }
    });
    const res =await response.json();
  
    clearInterval(progressInterval);
    onProgress({ percent: 100 });
    
    // 上传成功回调
    onSuccess(res.data, file);
    emit('uploadSuccess',res.data)
    message.success(`${file.name} 上传成功`);
  } catch (error) {
    onError(error);
    fileList.value = [];
    
    message.error(`${file.name} 上传失败`);
  }
};

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件!');
    return false;
  }
  
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
    return false;
  }
  
  return true;
};

// 文件变化处理
const handleChange = ({ file, fileList: newFileList }) => {
  fileList.value = newFileList;
};

// 预览处理
const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  window.open(file.url || file.preview, '_blank');
};

// 获取Base64
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};
</script>